/*
 * Copyright (c) Zhongkehonglue Technologies Co., Ltd. 2025. All rights reserved.
 * Description: Implementation of functions related to the DMC DEV module.
 * Author: wangchunyang
 * Create: 2025-05-23
 */

#include "dmcSendAction.h"
#include "dmcLog.h"
#include "dmcDevice.h"
#include "dmcEnv.h"

#ifdef LOG_TAG
#undef LOG_TAG
#endif
namespace DlnaDmc {

IXML_Document* DmcGetActionNode(const DmcActionInfo &actionInfo)
{
    IXML_Document *actionNode = nullptr;

    for (const auto& [paraName, paraValue] : actionInfo.paraInfo) {
        auto ret = UpnpAddToAction(&actionNode, actionInfo.actionName.c_str(),
        actionInfo.serviceType.c_str(), paraName.c_str(), paraValue.c_str());
        if (ret != UPNP_E_SUCCESS) {
            LOGE(" get action node error = %{public}ld", ret);
            ixmlDocument_free(actionNode);
            return nullptr;
        }
    }
    return actionNode;
}

dmc_int32 DmcSendAction(dmc_uint32 deviceId, const DmcActionInfo &actionInfo,
    IXML_Document **actionResult)
{
    std::string controlUrl;
    auto ret = DmcDevice::GetInstance().GetControlUrl(deviceId, actionInfo.serviceType, controlUrl);
    if (ret != DMC_SUCCESS) {
        return ret;
    }
    LOGI(" dmc send action, control url:%{public}s.", controlUrl.c_str());
    IXML_Document *actionNode = nullptr;
    if (actionInfo.paraInfo.empty()) {
        actionNode = UpnpMakeAction(actionInfo.actionName.c_str(), actionInfo.serviceType.c_str(), 0, nullptr);
    } else {
        actionNode = DmcGetActionNode(actionInfo);
    }
    if (actionNode == nullptr) {
        LOGE(" action node nullptr.");
        return DMC_FAILURE;
    }
    auto client = DmcEnv::GetInstance().GetClientHdl();
    ret = UpnpSendAction(client, controlUrl.c_str(), actionInfo.serviceType.c_str(), nullptr,
        actionNode, actionResult);
    ixmlDocument_free(actionNode);
    if (ret != UPNP_E_SUCCESS) {
        LOGE(" upnp send action error, %{public}d.", ret);
        return DMC_FAILURE;
    }
    return DMC_SUCCESS;
}
}





